import { defineStore } from "pinia";
import { createStorage } from "@/utils/storage";
import { CURRENT_USER } from "@/store/mutation-types";
import { login, logout } from "@/api/system/auth";
import { store } from "@/store";

const storage = createStorage({ storage: localStorage });

// 表单字段
export interface LoginInfo {
  username: string;
  password: string;
}

interface AuthState {
  // 用户信息
  userInfo: string;
  // 用户token
  token: string;
  // 登录的加载状态
  loginLoading: boolean;
}

export const useAuthStore = defineStore({
  id: "app-auth",
  state: (): AuthState => ({
    userInfo: "",
    token: storage.get(CURRENT_USER, ""),
    loginLoading: false,
  }),
  getters: undefined,
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    /**
     * 登录
     * @param params 用户信息
     */
    async login(params: LoginInfo) {
      this.loginLoading = true;
      try {
        const response = await login(params);
        console.log(response);
        const { name } = response;
        storage.set(CURRENT_USER, name);
      } catch (e) {
        return Promise.reject(e);
      } finally {
        this.loginLoading = false;
        console.log(this.loginLoading);
      }
    },
    async logout() {
      storage.remove(CURRENT_USER);
      try {
        await logout();
        return Promise.resolve("");
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
});

export const useAuthStoreOutSetup = () => {
  return useAuthStore(store);
};
